<template>
  <div class="wrap">
    <div class="title">
      <div class="add-wrap">
        <span>无用工设置时，按岗位最低等级价格计费</span>
        <el-button @click="add" v-if="mode == 1" type="primary" size="mini" icon="el-icon-circle-plus-outline">增加用工设置</el-button>
      </div>
      <div>
        <el-button v-if="mode === 0" @click="startEdit" type="text">编辑</el-button>
      </div>
    </div>

    <div class="list-wrap">
      <div class="list-item" v-for="(item, index) in list" :key="item.id">
        <el-select :disabled="mode === 0" v-model="item.industry" placeholder="行业" @change="id => changeIndustry(id, item)">
          <el-option
            v-for="it in industryJob"
            :key="it.id"
            :label="it.label_name"
            :value="it.id">
          </el-option>
        </el-select>

        <el-select :disabled="mode === 0" v-model="item.job" placeholder="岗位" @focus="focus(item)">
          <el-option
            v-for="it in computeJobOption(jobList, item)"
            :key="it.id"
            :label="it.label_name"
            :value="it.id">
          </el-option>
        </el-select>

        <el-select :disabled="mode === 0" v-model="item.level" placeholder="请选择">
          <el-option
            v-for="it in rankList"
            :key="it.id"
            :label="it.name"
            :value="it.id">
          </el-option>
        </el-select>

        <i v-if="!item.id && mode === 1" class="el-icon-delete" @click="remove(index)"></i>

        <em class="tips" v-if="item.shop_price >= 0">用工价格: {{item.shop_price}}元/小时</em>
      </div>
    </div>

    <div class="btns" v-if="list.length && mode === 1">
      <el-button type="default" size="mini" class="back" @click="back">返回</el-button>
      <el-button type="primary" size="mini" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script>
// 用工设置组件
import {getShopJobLevelList, shopJobRankList} from '@/api/shop'
import {fetchIndustryJob} from '../../../api/label'
import {getShopFee} from '../../../api/price'
import {saveShopJobLevel} from '../../../api/shop'
import {cloneDeep, orderBy} from 'lodash'

export default {
  name: 'useEmployeeSetting',
  props: {
    shop_sn: {
      type: String,
      required: true,
    },
    city_id: {
      type: Number | String,
      required: true,
    },
    area_id: {
      type: Number | String,
      required: true,
    },
    industry_id: {
      type: Number | String,
      required: true,
    }
  },
  data() {
    return {
      mode: 0, // 0只读 1编辑
      rankList: [],
      list: [],
      total: 0,
      industryJob: [], // 行业(岗位)列表
      jobList: [], // 当前岗位列表
    }
  },
  created() {
    this.fetchShopJobRankList()
    this.fetchShopJobList()
    this.fetchIndustryJob()
  },
  watch: {
    list: {
      handler(list) {
        list.forEach((it, index) => {
          if (it.industry && it.job && it.level) {
            this.fetchShopFee(it, index)
          }
        })
      },
      deep: true
    },
  },
  methods: {
    computeJobOption(val, level) {
      return val.length ? val : level.jobList
    },
    focus(it) {
      this.jobList = this.getJobListFromIndustry(it.industry, this.list, it.job)
    },
    remove(index) {
      this.list.splice(index, 1)
    },
    back() {
      this.mode = 0
      this.list = this.listBak
      delete this.listBak
    },
    startEdit() {
      this.mode = this.mode^1
      this.listBak = cloneDeep(this.list)
    },
    async save() {
      try {
        const hasEmptyItem = this.list.some(it => !it.industry || !it.job || !it.level)

        if (hasEmptyItem) {
          return this.$message.error('请完整填写用工等级设置')
        }

        const list = this.list.map(it => {
          const industryItem = this.industryJob.find(item => item.id === it.industry)
          const jobList = industryItem.children
          const label = jobList.find(itm => itm.id === it.job)
          return {
            id: it.id,
            industry: it.industry,
            label_name: label.label_name,
            label_id: it.job,
            job_level: it.level,
            shop_sn: this.shop_sn
          }
        })

        await saveShopJobLevel({
          add: list.filter(it => !it.id),
          update: list.filter(it => it.id),
          shop_sn: this.shop_sn
        })

        this.$message.success('保存成功')
        this.mode = 0
        delete this.listBak
        this.fetchShopJobList()
      } catch (err) {
        console.log('-----err', err)
      }
    },
    async fetchShopFee(data, index) {
      try {
        const ret = await getShopFee({
          city_id: this.city_id,
          area_id: this.area_id,
          shop_sn: this.shop_sn,
          industry: data.industry,
          label_id: data.job,
          type: data.level
        })

        this.list[index].shop_price = ret.shop_price / 100
        this.$forceUpdate()
      } catch (err) {
        console.log('-err', err)
        this.$message.error(err && err.msg || '获取商家基础价失败')
      }
    },
    add() {
      // 空列表不认为是未完成填写
      if (!this.list.length) {
        this.list.push({
          industry: '',
          job: '',
          level: ''
        })
        return
      }

      const hasEmptyItem = this.list.some(it => !it.industry || !it.job || !it.level)

      if (hasEmptyItem) {
        return this.$message.error('请添加未完成的项后再新增')
      }

      this.list.push({
        industry: '',
        job: '',
        level: ''
      })
    },
    // 通过行业id获取该行业下还未设置的岗位集合
    getJobListFromIndustry(industry, list=this.list, job='') {
      const industryItem = this.industryJob.find(it => it.id === industry)
      const allJobList = industryItem ? industryItem.children : []  // 当前行业下的岗位全集
      const yetJobList = list.filter(it => it.industry === industry).map(it => it.job) || [] // 已经设置的岗位集合
      const restJobList = allJobList.filter(it => !yetJobList.includes(it.id)) // 取得差集，即未设置的岗位集合
      const currentJobList = allJobList.filter(it => +it.id === +job) // 如果有job，则拼接上当前存在的岗位
      return [...currentJobList, ...restJobList]
    },
    changeIndustry(id, level) {
      level.jobList = this.getJobListFromIndustry(id)
      level.job = ''
      this.$forceUpdate()
    },
    async fetchShopJobRankList() {
      try {
        const rankList = await shopJobRankList()
        this.rankList = orderBy(rankList, ['id'], ['desc'])
      } catch (err) {
      }
    },
    async fetchShopJobList() {
      try {
        const ret = await getShopJobLevelList({
          shop_sn: this.shop_sn,
        })

        ret.list = ret.list.map(it => {
          return {...it, job: it.label_id, level: it.job_level}
        }).reverse()

        ret.list.forEach(it => {
          const jobList = this.getJobListFromIndustry(it.industry, ret.list)
          it.jobList = [...jobList, {id: it.label_id, label_name: it.label_name}]
        })

        this.list = ret.list
        this.total = ret.total
      } catch (err) {
        console.log('----err', err)
        this.$message.error(err && err.msg || '获取店铺设置的用工等级列表失败')
      }
    },
    async fetchIndustryJob() {
      try {
        const list = await fetchIndustryJob({city_id: this.city_id})
        this.industryJob = list.filter(it => +it.id === +this.industry_id)
      } catch (err) {
        console.log('-err', err)
      }
    },
  }
}
</script>

<style scoped lang="scss">
.wrap {
  width: 900px;
}
.title {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  .el-button {
    margin-left: 15px;
  }
}
.el-icon-delete {
  margin: 0 10px;
  cursor: pointer;
}
.list-wrap {
  margin-top: 40px;
}
.list-item {
  margin: 10px 0;
}
.tips {
  color: #D9001B;
  font-style: normal;
  margin-left: 5px;
}
.btns {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 60px;
  .back {
    margin-right: 40px;
  }
}
</style>



// WEBPACK FOOTER //
// src/components/shop/UseEmployeeSetting.vue